<?php

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Row;
use Encore\Admin\Tree;
use App\Models\Category;
use Encore\Admin\Layout\Content;
use Encore\Admin\Controllers\AdminController;

class CategoriesController extends AdminController
{
    protected $title = '分类管理';
	
	public function index(Content $content)
	{
		return $content
			->header($this->title())
			->title($this->title())
			->description($this->description['index'] ?? trans('admin.list'))
			->row(function (Row $row) {
				$tree = new Tree(new Category());
				
				$tree->disableCreate();
				
				$tree->branch(function ($branch) {
					$note = '';
					$category = Category::find($branch['id']);
					if ($category->hasChild() and $category->hasProduct()) {
						$note = '<span style="font-weight:bold;color:red">🚫-请转移商品至末级分类</span>';
					}
					return "{$branch['id']} - {$branch['name']} $note";
				});
				
				$row->column(6, $tree);
				$row->column(6, function (Column $column) {
					$column->append($this->form());
				});
			});
	}
	
    protected function form()
    {
        $form = new Form(new Category());

        $form->select('parent_id', '上级分类')->options(Category::selectOptions());
        $form->text('name', '分类名称')->rules('required');
        $form->text('name_mini', '分类简称');
        $form->image('image', '分类ICON')->uniqueName()->removable();
        $form->switch('is_show', '显示');
       /* $form->switch('is_default', '默认搜索为全部数据');*/
        
        //$form->select('transfer_id', '转移商品至')->options(Category::selectOptions());
        
        if (!preg_match('/edit/', request()->path())) {
        	$form->setAction(admin_base_path('categories'));
        }
        
        $this->formFooter($form);

        return $form;
    }
    
    protected function formFooter(Form $form)
    {
    	$form->footer(function (Form\Footer $footer) {
    		$footer->disableViewCheck();
    		$footer->disableCreatingCheck();
    		$footer->disableEditingCheck();
	    });
    }
}
